<template>
  <div class="page-container">
    <div class="add-wrap">
      <div class="header-section">
        <Breadcrumb :titles="titles"></Breadcrumb>
        <div class="title">
          <el-input
            placeholder="请输入园区名称"
            v-model="parameter.name"
            @keydown.enter.native="search"
            clearable
            @clear="search"
            class="title-input"
          >
            <span
              @click="search"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
          <el-input
            placeholder="请输入楼栋名称"
            v-model="parameter.buildName"
            @keydown.enter.native="search"
            clearable
            @clear="search"
            class="title-input"
          >
            <span
              @click="search"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
          <el-input
            placeholder="请输入户型"
            v-model="parameter.type"
            @keydown.enter.native="search"
            clearable
            @clear="search"
            class="title-input"
          >
            <span
              @click="search"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
          <el-date-picker
            v-model="currentSelect"
            type="month"
            @change="changeMonth"
            :clearable="false"
            placeholder="选择月"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </div>
      </div>

      <div class="table-section">
        <el-table
          :data="tableData"
          :header-cell-style="{
            background: '#F2F6FB',
            color: ' #6B767D'
          }"
          height="100%"
        >
          <el-table-column
            label="序号"
            align="center"
            show-overflow-tooltip
            width="80"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="年度"
            prop="year"
            show-overflow-tooltip
          />
          <el-table-column
            label="月份"
            prop="month"
            show-overflow-tooltip
          /> -->
          <el-table-column
            label="所属园区"
            prop="parkName"
            width="250"
            show-overflow-tooltip
          />
          <!-- <el-table-column
            label="所属楼栋"
            prop="buildName"
            show-overflow-tooltip
          /> -->
          <el-table-column
            label="户型"
            prop="type"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            label="户型总套数"
            prop="number"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            label="已销售套数(套)"
            prop="allNumber"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            label="剩余套数(套)"
            prop="remainNumber"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            label="本年度已完成(万元)"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-input
                type="number"
                class="num-input"
                v-model="scope.row.industryValue"
                :disabled="editable"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="本年度累计销售套数(套)"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-input
                type="number"
                class="num-input"
                v-model="scope.row.totalNumber"
                @input="
                  (value) =>
                    handleTotalNumberChange(
                      value,
                      scope.row
                    )
                "
                :disabled="editable"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="本年度销售面积(平方米)"
            min-width="120"
          >
            <template slot-scope="scope">
              <div>
                {{
                  scope.row.totalNumber && scope.row.area
                    ? formatNumber(
                        Number(scope.row.totalNumber) *
                          Number(scope.row.area)
                      )
                    : ''
                }}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="排序" width="140">
            <template slot-scope="scope"> -->
          <!-- <el-input
                class="num-input"
                v-model="scope.row.orderIndex"
                :disabled="editable"
              ></el-input> -->
          <!-- <div>{{ scope.row.pkid }}</div>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <div class="line">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import dayjs from 'dayjs'
import {
  addCommercialHouseProcess,
  queryCommercialHouseProcessById
} from '@/api/dataManagement'
import Icon from '@/components/icon'
import {
  isBeforeMonth,
  isAfterMonth
} from '@/utils/datetime'
import { formatNumber } from '@/utils/number'

export default {
  props: {
    title: String,
    projectId: String
  },
  components: {
    Icon,
    Breadcrumb
  },
  data() {
    return {
      tableData: [],
      currentSelect: '',
      parameter: {
        type: '',
        month: '',
        year: '',
        name: '',
        buildName: ''
      },
      currentNewSelect: '',
      pickerOptions: {
        disabledDate: (date) => {
          return isAfterMonth(date, new Date())
        }
      }
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    editable() {
      if (this.currentSelect && this.currentNewSelect) {
        return isBeforeMonth(
          this.currentSelect,
          this.currentNewSelect
        )
      }
      return false
    }
  },
  mounted() {
    const date = new Date()
    this.currentSelect = dayjs(date)
      .subtract(1, 'month')
      .format('YYYY-M')
    this.currentNewSelect = JSON.parse(
      JSON.stringify(this.currentSelect)
    )
    this.parameter.year = this.currentSelect.split('-')[0]
    this.parameter.month = this.currentSelect.split('-')[1]
    this.getProcessList()
  },
  methods: {
    formatNumber(value) {
      return formatNumber(value)
    },
    handleTotalNumberChange(value, item) {
      let inputValue = Math.abs(Math.floor(value))
      if (
        inputValue - item.oriTotalNumber >
        item.oriRemainNumber
      ) {
        this.$message.error('增加的数量不能大于剩余套数')
        inputValue =
          item.oriTotalNumber + item.oriRemainNumber
      }
      const diff = inputValue - item.oriTotalNumber

      item.allNumber = item.oriAllNumber + diff
      item.remainNumber = +item.number - +item.allNumber
      item.totalNumber = inputValue
    },
    handleNumberChange() {
      // const parkIdSumMap = {}

      // this.tableData.forEach((item) => {
      //   const key = item.parkId
      //   const number = Number(item.totalNumber) || 0
      //   parkIdSumMap[key] =
      //     (parkIdSumMap[key] || 0) + number
      // })

      this.tableData.forEach((item) => {
        // const soldNumber = parkIdSumMap[item.parkId] || 0
        // this.$set(item, 'soldNumber', soldNumber.toFixed(0))

        const totalNumber = Number(item.number) || 0
        const allNumber = Number(item.allNumber) || 0
        const remainNumber = totalNumber - allNumber
        this.$set(item, 'remainNumber', remainNumber)
      })
    },
    changeMonth() {
      if (this.currentSelect) {
        const select = dayjs(this.currentSelect).format(
          'YYYY-M'
        )
        this.parameter.year = select.split('-')[0]
        this.parameter.month = select.split('-')[1]
      }
      this.getProcessList()
    },
    getProcessList() {
      queryCommercialHouseProcessById(this.parameter).then(
        (res) => {
          if (res.success) {
            this.tableData = res.data.map((item) => {
              return {
                ...item,
                year: item.year
                  ? item.year
                  : this.parameter.year,
                month: item.month
                  ? item.month
                  : this.parameter.month,
                remainNumber:
                  Number(item.number) -
                  Number(item.allNumber),
                oriRemainNumber:
                  Number(item.number) -
                  Number(item.allNumber),
                oriNumber: +item.number,
                oriAllNumber: +item.allNumber,
                oriTotalNumber: +item.totalNumber
              }
            })
            // this.handleNumberChange()
          }
        }
      )
    },
    search() {
      this.getProcessList()
    },
    saveInfo() {
      addCommercialHouseProcess(this.tableData)
        .then((res) => {
          if (res.success) {
            this.$message.success('保存成功')
            this.$router.push({
              path: '/dataManagement/carrierReduction/commercialHouse/list'
            })
          } else {
            this.$message.error(res.message || '保存失败')
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/table.scss';
@import '~@/assets/css/form.scss';
.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.add-wrap {
  flex: 1;
  overflow: auto;
  padding: 10px 20px;
  height: 100%;

  .title {
    margin: 15px 0;
    display: flex;

    &-input {
      width: 220px;
      margin-right: 20px;
    }
  }
}

// .header-section {
//   padding: 10px 20px;
//   flex-shrink: 0;

//   .title {
//     margin: 15px 0;
//   }
// }

.line {
  flex-shrink: 0;
  padding: 10px;
  background: #fff;
  border-top: 1px solid #eee;
  text-align: center;
}

.save-btn {
  background: #497fa3;
  border: 1px solid #497fa3;
  width: 104px;
  color: white;
  font-size: 14px;
  width: 104px;
  height: 34px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}

.table-section {
  flex: 1;
  overflow: hidden;
}

.table-section ::v-deep .el-table__body-wrapper {
  overflow-y: auto !important;
}

::v-deep .num-input .el-input__inner {
  max-width: 120px;
}

::v-deep .el-input__icon {
  margin-top: -5px;
}
</style>
